<!DOCTYPE html>
<html>
<head>
    <title>Image Gallery</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 0;
            background-color: #f4f4f4;
        }

        h2 {
            text-align: center;
            margin: 20px 0;
            color: #333;
        }

        #image-container {
            display: flex;
            flex-direction: column;
            align-items: center;
            gap: 20px;
            padding: 20px;
            width: 50%;
            margin: 0 auto;
        }

        #image-container img {
            width: 100%;
            height: auto;
            border-radius: 5px;
        }

        .image-name {
            text-align: center;
            font-size: 0.9em;
            color: #666;
        }

        .pagination {
            display: flex;
            justify-content: center;
            gap: 10px;
            margin: 20px 0;
        }

        .pagination button {
            padding: 5px 10px;
            background-color: #333;
            color: #fff;
            border: none;
            border-radius: 5px;
            cursor: pointer;
        }

        .pagination button:disabled {
            background-color: #ccc;
            color: #666;
            cursor: not-allowed;
        }

        #loading {
            text-align: center;
            margin: 20px 0;
            display: none;
        }

        #page-info {
            text-align: center;
            margin: 10px 0;
            font-size: 0.9em;
            color: #555;
        }
    </style>
</head>
<body>
<h2>Image Gallery</h2>
<div id="image-container"></div>
<div id="loading">Loading images...</div>
<div id="page-info">Page 1 of 1</div>
<div class="pagination">
    <button id="prev-page">Previous Page</button>
    <button id="next-page">Next Page</button>
</div>

<script>
    const itemsPerPage = 5; // 每页显示的图片数量
    let currentPage = 1; // 当前页码
    let totalItems = 0; // 总图片数量
    let totalPages = 0; // 总页数

    // 获取图片数据
    function fetchImages(page) {
        const offset = (page - 1) * itemsPerPage;
        const limit = itemsPerPage;

        // 显示加载状态
        document.getElementById('loading').style.display = 'block';
        document.getElementById('image-container').innerHTML = ''; // 清空图片容器

        fetch(`https://dshmbsawwrbuycnivcjs.supabase.co/rest/v1/images?select=*&limit=${limit}&offset=${offset}`, {
            method: 'GET',
            headers: {
                'apikey': 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImRzaG1ic2F3d3JidXljbml2Y2pzIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NTM5Mjg2OTAsImV4cCI6MjA2OTUwNDY5MH0.fwRJD-WuST7mCbJf9h2i2Xk0z6mtCMCeV--JGUecC6A',
                'Authorization': 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImRzaG1ic2F3d3JidXljbml2Y2pzIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NTM5Mjg2OTAsImV4cCI6MjA2OTUwNDY5MH0.fwRJD-WuST7mCbJf9h2i2Xk0z6mtCMCeV--JGUecC6A',
                'Content-Type': 'application/json',
                'Prefer': 'return=minimal'
            }
        })
            .then(response => response.json())
            .then(data => {
                console.log('Fetched data:', data); // 调试信息
                displayImages(data);
            })
            .catch(error => {
                console.error('Error fetching images:', error);
                document.getElementById('loading').style.display = 'none'; // 隐藏加载状态
                alert('Failed to fetch images. Please check the URL and try again.');
            });
    }

    // 获取总数据量
    function fetchTotalItems() {
        fetch('https://dshmbsawwrbuycnivcjs.supabase.co/rest/v1/images?select=count', {
            method: 'GET',
            headers: {
                'apikey': 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImRzaG1ic2F3d3JidXljbml2Y2pzIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NTM5Mjg2OTAsImV4cCI6MjA2OTUwNDY5MH0.fwRJD-WuST7mCbJf9h2i2Xk0z6mtCMCeV--JGUecC6A',
                'Authorization': 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImRzaG1ic2F3d3JidXljbml2Y2pzIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NTM5Mjg2OTAsImV4cCI6MjA2OTUwNDY5MH0.fwRJD-WuST7mCbJf9h2i2Xk0z6mtCMCeV--JGUecC6A',
                'Content-Type': 'application/json',
                'Prefer': 'return=minimal'
            }
        })
            .then(response => response.json())
            .then(data => {
                console.log('Total items data:', data); // 调试信息
                // 解析返回的总数据量
                if (data.length > 0 && data[0].count !== undefined) {
                    totalItems = data[0].count; // 从返回的数组中提取 count 值
                    totalPages = Math.ceil(totalItems / itemsPerPage);
                    fetchImages(currentPage); // 加载当前页的数据
                } else {
                    console.error('Invalid total items response:', data);
                    alert('Failed to fetch total items. Please check the API response.');
                }
            })
            .catch(error => {
                console.error('Error fetching total items:', error);
                alert('Failed to fetch total items. Please check the URL and try again.');
            });
    }

    // 显示图片
    function displayImages(data) {
        const container = document.getElementById('image-container');
        container.innerHTML = ''; // 清空当前内容

        data.forEach(image => {
            const img = document.createElement('img');
            img.src = image.data;
            img.alt = image.name || 'No Name';

            const nameDiv = document.createElement('div');
            nameDiv.className = 'image-name';
            nameDiv.textContent = image.name || '';

            const imgWrapper = document.createElement('div');
            imgWrapper.appendChild(img);
            imgWrapper.appendChild(nameDiv);

            container.appendChild(imgWrapper);
        });

        // 更新分页按钮状态
        updatePaginationButtons();

        // 更新页码信息
        updatePageInfo();

        // 隐藏加载状态
        document.getElementById('loading').style.display = 'none';
    }

    // 更新分页按钮状态
    function updatePaginationButtons() {
        const prevButton = document.getElementById('prev-page');
        const nextButton = document.getElementById('next-page');

        prevButton.disabled = currentPage === 1;
        nextButton.disabled = currentPage === totalPages;
    }

    // 更新页码信息
    function updatePageInfo() {
        const pageInfo = document.getElementById('page-info');
        pageInfo.textContent = `Page ${currentPage} of ${totalPages}`;
    }

    // 监听分页按钮点击事件
    document.getElementById('prev-page').addEventListener('click', () => {
        if (currentPage > 1) {
            currentPage--;
            fetchImages(currentPage);
        }
    });

    document.getElementById('next-page').addEventListener('click', () => {
        if (currentPage < totalPages) {
            currentPage++;
            fetchImages(currentPage);
        }
    });

    // 初始化加载第一页
    fetchTotalItems();
</script>

<!-- 引入访客统计模块 -->
<script src="../visitor-tracker.js"></script>
<!-- Cloudflare Web Analytics -->
<script defer src='../lib/cloudflare/beacon.min.js' data-cf-beacon='{"token": "0e55e488041949479a3dace73ef940cd"}'>
</script>
<!-- End Cloudflare Web Analytics -->

</body>
</html>